Ext.ns("map");
map.panel = {};

map.init = function() {
	map.panel.make.main();
};

map.data = {};

map.statics = {};
map.statics.value1 = '정비소 이름을 검색하세요.';
map.statics.alert = function(value1 , value2) {
	new Ext.MessageBox({
		hideOnMaskTap:false,
		modal:true,
	}).alert(value1 , value2);
};
map.statics.getFromObj = function( src , name ) {
	if(src instanceof Document) {
		return $(src).find(name).text();
	}
	else {
		return src[name];
	}
};

map.statics.category1Icons = function() {
	
	var ctlDiv = document.createElement('DIV');
	$(ctlDiv).attr('id' , 'mapPanel_category1Btn').attr('cval' , 0);

	var ctl = new googlemap.Control( ctlDiv , map.data.gmap );
	ctlDiv.index = 1;
	map.data.gmap.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push( ctlDiv );
};





map.panel.make = {};
map.panel.make.main = function() {
	var htmlpage = "<iframe name='if1' src='/curmap.jsp?width="+  main.winWidth +"&height="+ main.winHeight +"' width='100%' , height='100%' frameborder='0' border='0' cellspacing='0' cellpadding='0' scrolling='1'></iframe>";
	htmlpage = "<div id='mainPanel_mapdiv'></div>";
	if(map.panel.main && main.reload) {
		map.panel.main.destroy();
	}

	map.panel.main = new Ext.Panel({
		fullscreen: true,
		dockedItems : [{
			dock: 'top',
			xtype: 'toolbar',
			title: '주변정비소',
			items: [map.btn.search , xt_spacer , map.btn.list]
		}],
		html: htmlpage,
		listeners : {
			'activate' : function() {
				if(!map.panel.main || !main.reload) {
					main.reload = true;
					return;
				}
				navigator.geolocation.getCurrentPosition( function(position){
					
					var lat = position.coords.latitude;
					var lng = position.coords.longitude;
					var distance = 10000;
					map.data.gmap = googlemap.makeMap( document.getElementById('mainPanel_mapdiv') ,
									   new google.maps.LatLng(lat , lng) , 
									   getCarcInfoAround('xml' , {'lat' : lat , 'lng' : lng , 'distance' : distance }) 
					);
					map.statics.category1Icons();
				} , function(){} , {enableHighAccuracy : true} );
			},
		},
	});	
};
map.panel.make.list = function(lat , lng) {
	var json = getCarcInfoAround('json' , {'lat' : lat , 'lng' :lng , 'distance' : 100000});
	var storex = new Ext.data.Store({
		model: 'carc_info',
		data : eval(json)
	});
	
	var itemTemplate = new Ext.XTemplate(
			'<div style="font-size:12px; "><div style="float:left; width:15%; ">&nbsp;{picture}</div><div style="font-size:12px; font-weight:bold;">{name}&nbsp;&nbsp;{avggrade} (<label style="color:#aaaaaa;">{grade_total_count}</label>)</div>'
			   , '<div style="margin-top:7px;">{description}</div>'
			   , '<div style="margin-top:7px;">**소분류아이콘**</div>'
			   , '</div>'		
	);
	
	var carc_list = new Ext.List({
		fullscreen:true,
		itemTpl: itemTemplate,
		store : storex,
		draggable : true,
		onItemDisclosure : function(record , btnDom , index){
			map.panel.make.carcenter(record.data);
		},
	});
	
	if(map.panel.list) map.panel.list.destroy();
	map.panel.list = new Ext.Panel({
		fullscreen: true,
		dockedItems: [{
			dock: 'top',
			xtype: 'toolbar',
			title: '검색결과',
			items: [map.btn.list.close]
		}],
		layout: {
			type: 'vbox',
			align: 'stretch',
			pack: 'center',
		},
		items: carc_list,
	});	
};

map.panel.make.search = function() {
	
	var data ='';
	data =  eval('('+getAddrTree()+')');
	var store = new Ext.data.TreeStore({
		model: 'menuList',
		root: data,
		
		proxy: {
			type: 'ajax',
			reader: {
				type: 'tree',
				root: 'items'
			}
		}
	});
	
	var nestedList = new Ext.NestedList({
		fullscreen: true,
		title: '전국',
		displayField: 'text',
		store : store,
		listeners : {
			'itemtap' : function(list , index , item , e) {
				var store = list.getStore();
				var record = store.getAt(index);
				
			//	record.data.text;
			//	record.node.leaf;
				if(record.node.leaf) {
					var htmlpage = "<iframe name='if1' src='/curmap.jsp?addr_gubun="+ record.node.parentNode.attributes.record.data.text + "&addr_dong="+record.data.text +"&width="+  main.winWidth +"&height="+ main.winHeight +"' width='100%' , height='100%' frameborder='0' border='0' cellspacing='0' cellpadding='0' scrolling='1'></iframe>";
					htmlpage = "<div id='mainPanel_mapdiv2'></div>";
					if(map.panel.search && main.reload) map.panel.search.destroy();
					map.panel.search = new Ext.Panel({
						fullscreen: true,
						html: htmlpage,
						dockedItems : [{
							dock: 'top',
							xtype: 'toolbar',
							title: '지역 검색',
							items: [map.btn.list.close , xt_spacer , map.btn.search.namesearch]
						}],
						listeners : {
							'activate' : function() {
								if(!map.panel.search || !main.reload) {
									main.reload = true;
									return;
								}
								var address = record.node.parentNode.attributes.record.data.text + record.data.text;
								var geocoder = new google.maps.Geocoder();
								geocoder.geocode( {'address' : address} , function(results ,status){
									if(status == google.maps.GeocoderStatus.OK) {
										map.data.gmap = googlemap.makeMap( document.getElementById('mainPanel_mapdiv2') ,
												 results[0].geometry.location  , 
												 getCarcInfo('xml' , '' , '' , '' , { addr_dong : record.data.text , addr_gubun : record.node.parentNode.attributes.record.data.text })
										);
									}
								} );
								
							},
						},
					});	
				//	main.panel.cardSwitchAnimation='slide';
				//	main.panel.layout.setActiveItem(map.panel.search);
				//	main.panel.doLayout();
					main.goPage('psearch' , 'slide');
				}
			}
		}, 
	});
	
	if(map.panel.search) map.panel.search.destroy();
	map.panel.search = new Ext.Panel({
		fullscreen: true,
		dockedItems : [{
			dock: 'top',
			xtype: 'toolbar',
			title: '지역 검색',
			items: [map.btn.list.close , xt_spacer , map.btn.search.namesearch]
		}],
		items : nestedList,
	});
};

map.panel.make.namesearch = function() {
	if(map.panel.namesearch) map.panel.namesearch.destroy();
	var itemTemplate = new Ext.XTemplate(
			'<div style="font-size:12px;">{name}</div>'		
	);
	map.data.ciStore = new Ext.data.Store({
		model: 'carc_info',
	});
	var carc_list = new Ext.List({
		fullscreen:true,
		itemTpl: itemTemplate,
		store : map.data.ciStore,
		draggable : true,
		onItemDisclosure : function(record , btnDom , index){
			map.panel.make.carcenter(record.data);
		},
	});
	map.panel.namesearch = new Ext.Panel({
		dockedItems : [{
			dock: 'top',
			xtype: 'toolbar',
			title: '<label style="font-size:14px">정비소명 검색</label>',
			items: [map.btn.search.namesearch.close , xt_spacer , map.btn.search.namesearch.search]
		},{
			dock : 'bottom',
			xtype: 'textfield',
			value: map.statics.value1,
			style: 'font-size:12px;',
			listeners: {
				'focus' : function(el , e){
					if(el.getValue() == map.statics.value1) {
						el.setValue('');
					}
				},
				'blur' : function(el , e) {
					if(el.getValue() == '') {
						el.setValue(map.statics.value1);
					}
				},
			}
		},],
		layout: {
			type: 'vbox',
			align: 'stretch',
			pack: 'center',
		},
		items : carc_list,
		
	});
};

map.panel.make.carcenter = function( param ){
	
	var carc_info;
	if( typeof param == 'object') {
		
		carc_info = param;
		
		if( param instanceof Document ) {
			// xml dom object type 이라면..
		//	carc_info = $(param);
		}
		else {
			
		}
	}
	else if( typeof param == 'number' ) {
		carc_info = getCarcInfo('xml' , '' , '' , '' , { 'info_seq' : param });
	}
	
	var contentString = 
		  '<div style="padding:7px; font-size:12px;">'
		+ '<div style="height:100px; min-width:20%; float:left; border:1px solid gray; margin:6px;"	>사진없음.</div>'
		+ '<div style="height: 25px; float:left;"													>#평점표시란#</div>'
		+ '<div style="height: 25px; float:right;"													>#평가하기버튼#</div>'
		+ '<div style="height: 25px; clear:right;" class="ntext"									>#정비소설명#</div>'
		+ '<div style="height: 25px; "																>#대분류아이콘#</div>'
		+ '<div style="height: 25px; "																>#소분류아이콘#</div>'
		+ '<div style="height: 25px; "																>#사진등록버튼#</div>'
		+ '</div>'
		+
		  '<div style="padding:7px; font-size:12px;">'
		+ '<div style="height:25px; float:left;" class="ntext"										>#주소#</div>'
		+ '<div style="height:25px; float:right;"													>#지도보기버튼#</div>'
		+ '</div>'
		+
		'<div style="padding:7px; font-size:12px; clear:both;">'
		+ '<div style="height:25px; float:left;" class="ntext"										>#전화번호#</div>'
		+ '<div style="height:25px; float:right;"													>#전화하기버튼#</div>'
		+ '</div>'
		+
		'<div style="padding:7px; font-size:12px; clear:both;">'
		+ '<div style="height:25px; font-weight:bold; float:left;"									>상세노트</div>'
		+ '<div style="clear:both;" class="ntext"													>#상세내용#</div>'
		+ '</div>'
		+
		'<div style="padding:7px; font-size:12px; clear:both;">'
		+ '<div style="height:25px; font-weight:bold; float:left;"									>#평가글#</div>'
		+ '<div style="clear:both;" class="ntext" 													>#평가내용#</div>'
		+ '</div>'
		+
		'<div style="padding:7px; font-size:12px; clear:both;">'
		+ '<div style="height:25px; float:left;"													><!--평가글 남기기 버튼--></div>'
		+ '</div>';
	
	
	
	if( map.statics.getFromObj(carc_info , 'addr')  ) 		contentString = contentString.replace("#주소#"		, map.statics.getFromObj(carc_info , 'addr') );
	if( map.statics.getFromObj(carc_info , 'phone') ) 		contentString = contentString.replace("#전화번호#" 	, map.statics.getFromObj(carc_info , 'phone') );
	if( map.statics.getFromObj(carc_info , 'description') )	contentString = contentString.replace("#정비소설명#" , map.statics.getFromObj(carc_info , 'description') );
	if( map.statics.getFromObj(carc_info , 'detail_desc') )	contentString = contentString.replace("#상세내용#" 	, map.statics.getFromObj(carc_info , 'detail_desc') );
	
	contentString = contentString.replace("#평가하기버튼#" 
			, "<span class='button1' onclick='map.panel.make.eval_insert();'>평가하기</span>");
	
	contentString = contentString.replace("#지도보기버튼#" 
			, "<span class='button2' onclick='alert(1)'>지도보기</span>");
	
	contentString = contentString.replace("#전화하기버튼#" 
			, "<span class='button2' onclick='alert(1)'>전화하기</span>");
	
	contentString = contentString.replace("#평점표시란#" 
			, map.statics.getFromObj(carc_info , 'avggrade') + " / 10" + "&nbsp;&nbsp;<span style='color:red;'>("+ map.statics.getFromObj(carc_info , 'grade_total_count') +"명)</span>" );

	console.log( carc_info );
	contentString = contentString.replace("#평가글#" 
			, "평가글<span style='color:red;'>("+ map.statics.getFromObj(carc_info , 'grade_total_count') +")</span>&nbsp;&nbsp;"
	 );
	
	var eval_data =eval( getEvalInfo('json' , '' , '' , '' , { 'info_seq' : map.statics.getFromObj(carc_info , 'info_seq') }) );
	
	console.log(eval_data);
	
	contentString = contentString.replace("#평가내용#" 
			, "<div onclick='map.panel.make.carcenter_eval("+ map.statics.getFromObj(carc_info , 'info_seq') +")'>"
			+ "<div style='font-weight:bold; float:left;'>"+ eval_data[0].writer_name +"</div><div style='float:right;'>"+ eval_data[0].recent_dateymd +"</div>"
			+ "<div style='clear:both; padding: 10px 4px 3px 4px;'>" + eval_data[0].content + "</div>"
			+ "</div>");
	
	var favObj = new fav.statics.storageitem();
	
	favObj.info_seq = map.statics.getFromObj(carc_info , 'info_seq');
	favObj.name = map.statics.getFromObj(carc_info , 'name');
	favObj.category1 = map.statics.getFromObj(carc_info , 'category1');
	
	var favIcons = '';
	if( fav.statics.favorites.getByObject( favObj ) == undefined ) {
		favIcons = '☆';
	}
	else {
		favIcons = '★';
	}
	
	map.panel.carcenter = new Ext.Panel({
		dockedItems : [{
			dock: 'top',
			xtype: 'toolbar',
			title: '정비소',
			items: [map.btn.list.close],
		},{
			dock: 'top',
			xtype: 'tabbar',
			style : 'background:#feddaa;',
			items: [{
				xtype: 'tab',
				text :  map.statics.getFromObj(carc_info , 'name'),
			} , 
			xt_spacer ,
			{
				xtype: 'tab',
				text : favIcons,
				handler : function() {
					if( fav.statics.favorites.getByObject( favObj ) == undefined ) {
						fav.statics.favorites.put( favObj );
						this.setText('★');
					}
					else {
						fav.statics.favorites.remove( fav.statics.favorites.getIdx( favObj ) );
						fav.statics.favorites.setStorage();
						this.setText('☆');
					}
					
				}
			}],
		}],
		items: [
		    {
		    	html: contentString
		    		,
		    },
		],
	});
	/*
	var json = getEvalInfo('json' , '' , '' , '' , { 'info_seq' : map.statics.getFromObj(carc_info , 'info_seq') })
	
	var storex = new Ext.data.Store({
		model: 'carc_evaluation',
		data : eval(json)
	});
	
	var itemTemplate = new Ext.XTemplate(
			'<div style="font-size:12px;">'
			   , '<div style="margin-top:7px;">{description}</div>'
			   , '<div style="margin-top:7px;">**소분류아이콘**</div>'
			   , '</div>'		
	);
	
	var eval_list = new Ext.List({
		renderTo: 'carcenter_eval_div',
		fullscreen:true,
		itemTpl: itemTemplate,
		store : storex,
		draggable : true,
		onItemDisclosure : function(record , btnDom , index){
			map.panel.make.carcenter(record.data);
		},
	});

	map.panel.carcenter_eval = new Ext.Panel({
		renderTo: 'carcenter_eval_div',
		items : [eval_list] ,
	});
	*/
	main.goPage('pcarcenter' , 'slide');
	
};

map.panel.make.carcenter_eval = function( info_seq ) {
	var json = eval( getEvalInfo('json' , '' , '' , '' , { 'info_seq' : info_seq }) );
	
	var storex = new Ext.data.Store({
		model: 'carc_evaluation',
		data : json
	});
	
	console.log( json );
	
	var itemTemplate = new Ext.XTemplate(
			'<div style="font-size:12px;">'
			   , '<div style="margin-top:7px; font-weight:bold; float:left;">{writer_name}</div>'
			   , '<div style="margin-top:7px; font-weight:bold; float:right;">{recent_dateymd}</div>'
			   , '<div style="padding: 10px 4px 3px 4px; clear:both;">{content}</div>'
			   , '</div>'		
	);
	
	var eval_list = new Ext.List({
		fullscreen:true,
		itemTpl: itemTemplate,
		store : storex,
		draggable : true,
	});

	map.panel.carcenter_eval = new Ext.Panel({
		fullscreen: true,
		dockedItems: [{
			dock: 'top',
			xtype: 'toolbar',
			title: '정비소 평가 리스트',
			items: [map.btn.carcenter_eval.close]
		}],
		layout: {
			type: 'vbox',
			align: 'stretch',
			pack: 'center',
		},
		items: eval_list,
	});
	
	main.goPage('peval' , 'slide');
};

map.panel.make.eval_insert = function(info_seq) {
	
	var overlayToolbar = new Ext.Toolbar({
		dock : 'top',
		title : '평가입력',
	});
	
	map.panel.eval_insert = new Ext.form.FormPanel({
		floating: true,
		modal: true,
		centered: true,
		width:300,
		height:300,
		dockedItems: overlayToolbar,
		items:[
		       {
		    	   xtype: 'textfield',
		    	   label: 'aa',
		       },
		       {
		    	   text: '222222222'
		       },
		]
	});
	map.panel.eval_insert.show();
};

map.btn = {};
map.btn.search = {
	text : '검색',
	handler : function(btn , event) {
		if(!map.panel.search) map.panel.make.search();
		else { // else 를 뺄까 말까..
			map.panel.search.destroy();
			map.panel.make.search();
		}
		main.goPage('psearch' , 'pop');
	},
	namesearch : {
		text : '상호명검색',
		handler : function(btn , event) {
			map.panel.make.namesearch();
			main.goPage('pnamesearch' , 'pop');
		},
		close : {
			text : '닫기',
			handler : function(btn , event) {
				main.reload = false;
				main.goPage('psearch' , 'fade');
			}
		},
		search : {
			text : '검색',
			handler : function(btn , event) {
				var searchvalue = map.panel.namesearch.dockedItems.items[1].getValue();
				if( searchvalue == '' || searchvalue == map.statics.value1  ) {
					map.statics.alert('경고' , '값이 없습니다.');
					return;
				}
				
				var json = getCarcInfo('json' , '' , '' , '' , { 'name' : searchvalue })
				map.data.ciStore.loadData( eval(json) );
			}
		}
	}
};

map.btn.list = {
	text : '리스트',
	handler : function(btn , event) {
		
		navigator.geolocation.getCurrentPosition(function(position){
			var lat = position.coords.latitude;
			var lng = position.coords.longitude;
			
			map.panel.make.list(lat , lng);
			main.goPage('plist' , 'pop');
		});
		
	},
	close : {
		text : '닫기',
		handler : function(btn , event) {
			main.reload = false;
			main.goPage('' , 'fade');
		}
	},
};

map.btn.carcenter_eval = {
	close : {
		text : '닫기',
		handler : function(btn , e) {
			main.goPage('pcarcenter' , 'fade');
		}
	}
}